<template>
  <div class="page-container">
    <div class="container">
      <!-- 导航返回 -->
      <el-page-header content="个人主页" @back="handleGoBack" />

      <!-- 个人信息区域 -->
      <div class="profile-header" :style="{ backgroundImage: `url(${backgroundImage})` }">
        <div class="header-overlay"></div>
        <div v-if="!hasUser" class="header-actions">
          <div></div>
          <el-button class="menu-button" @click="handleReport" icon="el-icon-warning" circle size="mini" />
        </div>
        <div class="profile-content">
          <div class="avatar-container">
            <el-image class="avatar" :src="avatarIcon" @click="previewAvatar" fit="cover" />
          </div>
          <div v-if="user" class="profile-info">
            <div class="username">
              {{ user.name }}
              <el-image
                class="vip-icon"
                v-if="user.vip === 1"
                :src="require('@/assets/images/yuedu.png')"
                :width="20"
                :height="20"
              />
              <el-image
                class="vip-icon"
                v-if="user.vip === 2"
                :src="require('@/assets/images/zuanshi.png')"
                :width="20"
                :height="20"
              />
              <el-image
                class="vip-icon"
                v-if="user.vip === 3"
                :src="require('@/assets/images/jika.png')"
                :width="20"
                :height="20"
              />
            </div>
            <div class="user-id">ID: {{ user.open_id || user.openid || '--' }}</div>
          </div>
        </div>
      </div>

      <!-- 个人标签区域 -->
      <div v-if="user.profile || (tagList && tagList.length)" class="profile-section tags-section">
        <div v-if="user.profile" class="bio-content">
          {{ user.profile || '' }}
        </div>
        <div v-if="tagList && tagList.length" class="tags-container">
          <el-tag
            :style="{ 'background-color': item.bg_color, color: item.color }"
            v-for="(item, index) in tagList"
            :key="index"
          >
            {{ item.name }}
          </el-tag>
        </div>
      </div>

      <!-- 数据统计区域 -->
      <div class="profile-section stats-section">
        <div class="stats-container">
          <div class="stat-item" @click="getHuozan(user.like_count)">
            <div class="stat-number">{{ user.like_count }}</div>
            <div class="stat-label">获赞</div>
          </div>
          <div class="stat-item" @click="getGuanzhu()">
            <div class="stat-number">{{ user.follow_count }}</div>
            <div class="stat-label">关注</div>
          </div>
          <div class="stat-item" @click="getFensi()">
            <div class="stat-number">{{ user.follower_count }}</div>
            <div class="stat-label">粉丝</div>
          </div>
        </div>
      </div>

      <!-- 关注按钮 -->
      <div v-if="!hasUser && user" class="concern-box">
        <el-button v-if="user.is_mutual == '1'" type="text" class="concern-btn" @click="handleFollow">
          <i class="el-icon-user-follow"></i>
          互相关注
        </el-button>
        <el-button v-else-if="user.is_follow == '1'" type="text" class="concern-btn" @click="handleFollow">
          <i class="el-icon-user-solid"></i>
          已关注
        </el-button>
        <el-button v-else type="primary" class="un-concern-btn" @click="handleFollow">+ 关注</el-button>
      </div>

      <!-- 作品展示区域 -->
      <div class="profile-section works-section">
        <WorkCard :workList="worksList" @handleWork="handleWork" />
        <div v-if="loading" class="load-more">
          <el-icon-loading />
          <span class="loading-text">加载中...</span>
        </div>
      </div>

      <!-- 获赞提示弹窗 -->
      <el-dialog title="获赞统计" :visible.sync="showHuo" width="30%" append-to-body>
        <div class="dialog-content">{{ contentHuo }}</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showHuo = false">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { myWorkList, getUserInfo, userFollow } from '@/api/workList'
import WorkCard from '@/components/workCard.vue'
export default {
  name: 'PersonalHome',
  components: {
    WorkCard,
  },
  data() {
    return {
      backgroundImage: '',
      avatarIcon: '',
      pages: {
        cursor: 0,
        limit: 20,
      },
      tagList: [],
      showHuo: false,
      loading: false,
      loadingAll: false,
      contentHuo: '',
      worksList: [],
      open_id: '',
      user: null,
    }
  },
  computed: {
    ...mapState(['userInfo']),
    hasUser() {
      if (!this.user) return false
      const { open_id } = this.user
      const { openid } = this.userInfo
      return open_id === openid
    },
  },
  async mounted() {
    // 优先使用props传递的open_id，兼容其他页面跳转传参
    const targetOpenId = this.$route.query.opid
    if (targetOpenId) {
      this.open_id = targetOpenId
      await this.getOtherUserInfo(targetOpenId)
    } else {
      // 无传入参数时显示当前登录用户信息
      this.user = this.userInfo
    }
    // 初始化背景图和头像
    this.backgroundImage = this.user.backdrop || ''
    this.avatarIcon = this.user.icon || require('@/assets/images/default-avatar.jpeg')
    // 获取作品列表
    this.getMyCreations()
    // 绑定滚动事件
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 返回上一页
    handleGoBack() {
      this.$router.go(-1)
    },
    // 关注操作
    async handleFollow() {
      const { is_follow } = this.user
      if (+is_follow === 1) {
        this.$confirm('确认取消关注？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.handleFollowFun()
          })
          .catch(() => {
            this.$message.info('已取消操作')
          })
      } else {
        this.handleFollowFun()
      }
    },
    // 获赞提示
    getHuozan(val) {
      this.contentHuo = val === 0 ? '还没有获赞' : `一共获得了 ${val} 个赞`
      this.showHuo = true
    },
    // 跳转关注列表
    getGuanzhu() {
      if (this.user.privacy.allow_follow_follower === 0) {
        this.$message.error('因用户隐私设置，无法查看')
        return
      }
      this.$router.push({
        path: '/followList',
        query: { openid: this.user.open_id },
      })
    },
    // 跳转粉丝列表
    getFensi() {
      if (this.user.privacy.allow_follow_follower === 0) {
        this.$message.error('因用户隐私设置，无法查看')
        return
      }
      this.$router.push({
        path: '/fanList',
        query: { openid: this.user.open_id },
      })
    },
    // 预览头像
    previewAvatar() {
      if (this.avatarIcon.includes('default-avatar')) {
        this.$message.warning('默认头像暂不支持放大查看哦')
        return
      }
      // PC端可通过新窗口打开预览
      window.open(this.avatarIcon, '_blank', 'width=600,height=600')
    },
    // 执行关注/取消关注接口
    async handleFollowFun() {
      // const loadingInstance = ElLoading.service({ text: '操作中...' })
      try {
        const { open_id, is_follow } = this.user
        const { code, msg } = await userFollow({ open_id })
        if (code === 200) {
          const isFollowNew = +is_follow === 1 ? 0 : 1
          this.user.is_follow = isFollowNew
          if (isFollowNew === 0) {
            this.user.is_mutual = 0
          }
          // 同步到vuex
          this.$store.dispatch('setUpdateFollow', {
            is_follow: isFollowNew,
            open_id,
          })
          this.$message.success(+is_follow === 1 ? '取消关注成功' : '关注成功')
        } else {
          this.$message.error(msg || '操作失败')
        }
      } catch (error) {
        this.$message.error('操作失败')
        console.error(error)
      }
    },
    // 获取其他用户信息
    async getOtherUserInfo(open_id) {
      try {
        const { code, data, msg } = await getUserInfo({ open_id })
        if (code === 200) {
          const { profile, statistics } = data
          this.user = { ...data, ...profile, ...statistics }
          this.tagList = this.user.tags || []
        } else {
          this.$message.error(msg || '获取用户信息失败')
        }
      } catch (error) {
        this.$message.error('获取用户信息失败')
        console.error(error)
      }
    },
    // 作品点击事件
    handleWork(item) {
      if (item.status === 2 && item.is_public === 0) {
        this.$router.push({
          path: '/releaseEdit',
          query: { workDetail: JSON.stringify(item) },
        })
      } else if (item.is_public === 1) {
        this.$store.dispatch('setExploreDetail', item)
        this.$store.dispatch('setPersonalWorks', this.worksList)
        this.$router.push({
          path: '/personalWorks',
          query: { from: 'explore' },
        })
      }
    },
    // 获取作品列表
    async getMyCreations() {
      if (this.loading || this.loadingAll) return
      this.loading = true
      const params = { ...this.pages }
      if (this.open_id) {
        params.open_id = this.open_id
      }
      try {
        const { code, data, msg } = await myWorkList(params)
        if (code === 200) {
          const { next_cursor, items } = data
          if (items.length < this.pages.limit) {
            this.loadingAll = true
          }
          this.worksList = [...this.worksList, ...items]
          this.pages.cursor = next_cursor || 0
        } else {
          this.$message.error(msg || '获取作品列表失败')
        }
      } catch (error) {
        this.$message.error('获取作品列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 举报
    handleReport() {
      this.$router.push({
        path: '/report',
        query: { openid: this.user.open_id },
      })
    },
    // 滚动加载更多
    handleScroll() {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
      const clientHeight = document.documentElement.clientHeight || window.innerHeight
      if (scrollTop + clientHeight >= scrollHeight - 200 && !this.loading && !this.loadingAll) {
        this.getMyCreations()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #121212;
  min-height: 100vh;
  color: #fff;
}

.container {
  width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
}

.el-page-header {
  margin-bottom: 30px;
  .el-page-header__content {
    color: #fff !important;
    font-size: 24px !important;
  }
  .el-page-header__left {
    .el-icon-back {
      color: #fff !important;
    }
  }
}

/* 个人信息区域 */
.profile-header {
  position: relative;
  height: 280px;
  background-size: cover;
  background-position: center;
  border-radius: 12px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
  }
}

.header-actions {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 2;
}

.menu-button {
  background-color: rgba(0, 0, 0, 0.5) !important;
  color: #fff !important;
}

.profile-content {
  position: relative;
  display: flex;
  padding: 0 40px;
  z-index: 2;

  .avatar-container {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
    border: 3px solid rgba(255, 255, 255, 0.8);
    margin-right: 30px;
    cursor: pointer;
  }

  .avatar {
    width: 100%;
    height: 100%;
  }
}

.profile-info {
  display: flex;
  flex-direction: column;
  justify-content: center;

  .username {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }

  .vip-icon {
    margin-left: 10px;
  }

  .user-id {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.7);
  }
}

/* 个人标签区域 */
.profile-section {
  margin-bottom: 30px;
}

.bio-content {
  font-size: 16px;
  color: #d1d5db;
  line-height: 1.6;
  margin-bottom: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.el-tag {
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 14px;
}

/* 数据统计区域 */
.stats-container {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.stat-item {
  width: 180px;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    background: rgba(255, 255, 255, 0.08);
  }

  .stat-number {
    font-size: 28px;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 10px;
  }

  .stat-label {
    font-size: 16px;
    color: #999;
  }
}

/* 关注按钮 */
.concern-box {
  margin-bottom: 30px;
  text-align: right;

  .concern-btn {
    color: #fff !important;
    border: 1px solid #444 !important;
    padding: 8px 20px;
  }

  .un-concern-btn {
    background-color: #ff2d55 !important;
    border-color: #ff2d55 !important;
    padding: 8px 20px;
  }
}

/* 作品区域 */
.works-section {
  margin-top: 20px;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 30px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;

  .loading-text {
    margin-left: 10px;
    font-size: 14px;
  }
}

/* 弹窗样式 */
.dialog-content {
  text-align: center;
  padding: 20px 0;
  font-size: 16px;
}
</style>
